#include <inning.h>

inning::inning( std::vector<player *> * roster ) {
	this->hits = 0;
	this->outs = 0;

	this->roster = roster;

	this->first_base   = NULL;
	this->second_base  = NULL;
	this->third_base   = NULL;
}

void inning::note_hit( player * at_bat ) {
	if ( third_base != NULL ) {
		output_dbug(third_base->getStat("name")->getValue());
		output_dbug("Score.");
		++hits;
		third_base = NULL;
	}
	if ( second_base != NULL ) {
		output_dbug(second_base->getStat("name")->getValue());
		output_dbug("On third");
		third_base = second_base;
		second_base = NULL;
	}
	if ( first_base != NULL ) {
		output_dbug(first_base->getStat("name")->getValue());
		output_dbug("On second");
		second_base = first_base;
		first_base = NULL;
	}
	first_base = at_bat;
}

void inning::run() {
	while ( this->outs < 3 ) {
		player * at_bat = this->nextUp();
		stats  * obp = at_bat->getStat("obp");

		stats  * doub = at_bat->getStat("_2b_pct");
		stats  * trip = at_bat->getStat("_3b_pct");  // XXX: Convert from current system to 1B, 2B, 3B HR / AB
		stats  * home = at_bat->getStat("_3b_pct");  //      do that at runtime and store in the player collection.

		std::string name = at_bat->getStat("name")->getValue();

		output_dbug(name);

		if ( obp->processValue() ) {
			this->note_hit( at_bat );
			output_dbug("We've got a hit");
			if ( doub->processValue() ) {
				this->note_hit( NULL );
				output_dbug("On to second!");
			} else if ( trip->processValue() ) {
				this->note_hit( NULL );
				this->note_hit( NULL );
				output_dbug("On to third!");
			} else if ( home->processValue() ) {
				this->note_hit( NULL );
				this->note_hit( NULL );
				this->note_hit( NULL );
				output_dbug("HOMERUNNNNNNNNNN");
			}
		} else {
			++outs;
			std::stringstream ss;
			ss << "Outs: " << this->outs;
			std::string outz = ss.str();
			output_dbug( outz );
		}
	}
	output_dbug("That's an inning!");
	std::stringstream ss;
	ss << "Hits: " << this->hits;
	std::string hitz = ss.str();

	output_dbug(hitz);
}

int inning::get_score() {
	return this->hits;
}

player * inning::nextUp() {
	player * at_bat = this->roster->at(0);
	this->roster->erase( this->roster->begin() );
	this->roster->push_back( at_bat );
	return at_bat;
}

